package com.logistics.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.logistics.entity.SysPermission;
import com.logistics.entity.SysRole;
import com.logistics.entity.SysUser;
import com.logistics.mapper.SysPermissionMapper;
import com.logistics.mapper.SysRoleMapper;
import com.logistics.mapper.SysUserMapper;
import com.logistics.common.TenantContextHolder;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.core.type.TypeReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 权限服务类
 */
@Service
public class PermissionService {
    
    @Autowired
    private SysPermissionMapper permissionMapper;
    
    @Autowired
    private SysUserMapper userMapper;
    
    @Autowired
    private SysRoleMapper roleMapper;
    
    @Autowired
    private ObjectMapper objectMapper;
    
    /**
     * 获取权限树（用于管理界面）
     */
    public List<SysPermission> getPermissionTree() {
        Long tenantId = TenantContextHolder.getTenantId();
        
        LambdaQueryWrapper<SysPermission> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysPermission::getTenantId, tenantId)
               .eq(SysPermission::getStatus, 1)
               .orderByAsc(SysPermission::getParentId, SysPermission::getSortOrder);
        
        return permissionMapper.selectList(wrapper);
    }
    
    /**
     * 将扁平的权限列表转换为树形结构
     */
    public List<Map<String, Object>> buildPermissionTree(List<SysPermission> permissions) {
        // 按父ID分组
        Map<Long, List<SysPermission>> permissionMap = permissions.stream()
                .collect(Collectors.groupingBy(p -> p.getParentId() == null ? 0L : p.getParentId()));
        
        return buildTree(0L, permissionMap);
    }
    
    private List<Map<String, Object>> buildTree(Long parentId, Map<Long, List<SysPermission>> permissionMap) {
        List<Map<String, Object>> tree = new ArrayList<>();
        List<SysPermission> children = permissionMap.get(parentId);
        
        if (children != null) {
            for (SysPermission permission : children) {
                Map<String, Object> node = new java.util.HashMap<>();
                node.put("key", permission.getId());
                node.put("title", permission.getPermissionName());
                node.put("permissionCode", permission.getPermissionCode());
                node.put("permissionType", permission.getPermissionType());
                
                // 递归获取子节点
                List<Map<String, Object>> subChildren = buildTree(permission.getId(), permissionMap);
                if (!subChildren.isEmpty()) {
                    node.put("children", subChildren);
                }
                
                tree.add(node);
            }
        }
        
        return tree;
    }
    
    /**
     * 根据用户ID获取权限代码列表
     */
    public List<String> getUserPermissionCodes(Long userId) {
        // 获取用户信息
        SysUser user = userMapper.selectById(userId);
        if (user == null) {
            return new ArrayList<>();
        }
        Long tenantId = user.getTenantId();
        
        // 如果用户有角色ID，从角色获取权限
        if (user.getRoleId() != null) {
            SysRole role = roleMapper.selectById(user.getRoleId());
            if (role != null && role.getPermissions() != null && !role.getPermissions().isEmpty()) {
                try {
                    return objectMapper.readValue(role.getPermissions(), new TypeReference<List<String>>() {});
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        
        // 如果没有 roleId，但有内置角色代码（如 SUPER_ADMIN / SITE_ADMIN），
        // 尝试根据 tenantId + roleCode 从 sys_role 表加载权限
        if (user.getRole() != null && !user.getRole().isEmpty()) {
            LambdaQueryWrapper<SysRole> roleWrapper = new LambdaQueryWrapper<>();
            roleWrapper.eq(SysRole::getTenantId, tenantId)
                       .eq(SysRole::getRoleCode, user.getRole());
            SysRole role = roleMapper.selectOne(roleWrapper);
            if (role != null && role.getPermissions() != null && !role.getPermissions().isEmpty()) {
                try {
                    return objectMapper.readValue(role.getPermissions(), new TypeReference<List<String>>() {});
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        
        return new ArrayList<>();
    }
    
    /**
     * 创建权限
     */
    public SysPermission createPermission(SysPermission permission) {
        Long tenantId = TenantContextHolder.getTenantId();
        permission.setTenantId(tenantId);
        permissionMapper.insert(permission);
        return permission;
    }
    
    /**
     * 更新权限
     */
    public void updatePermission(SysPermission permission) {
        permissionMapper.updateById(permission);
    }
    
    /**
     * 删除权限
     */
    public void deletePermission(Long id) {
        permissionMapper.deleteById(id);
    }
    
    /**
     * 获取用户角色信息（包含角色类型）
     * 用于前端权限计算
     */
    public List<com.logistics.vo.LoginResponse.RoleInfo> getUserRoleInfos(Long userId) {
        List<com.logistics.vo.LoginResponse.RoleInfo> roleInfos = new ArrayList<>();
        
        // 获取用户信息
        SysUser user = userMapper.selectById(userId);
        if (user == null) {
            return roleInfos;
        }
        
        Long tenantId = user.getTenantId();
        SysRole role = null;
        
        // 优先从 roleId 获取角色
        if (user.getRoleId() != null) {
            role = roleMapper.selectById(user.getRoleId());
        }
        // 否则根据 role 字段查询
        else if (user.getRole() != null && !user.getRole().isEmpty()) {
            LambdaQueryWrapper<SysRole> roleWrapper = new LambdaQueryWrapper<>();
            roleWrapper.eq(SysRole::getTenantId, tenantId)
                       .eq(SysRole::getRoleCode, user.getRole());
            role = roleMapper.selectOne(roleWrapper);
        }
        
        if (role != null) {
            com.logistics.vo.LoginResponse.RoleInfo roleInfo = new com.logistics.vo.LoginResponse.RoleInfo(
                role.getId(),
                role.getRoleCode(),
                role.getRoleType(),
                role.getFixedPermission()
            );
            roleInfos.add(roleInfo);
        }
        
        return roleInfos;
    }
    
    /**
     * 获取用户自定义权限码（可编辑角色的权限）
     * 固定权限角色返回空列表，可编辑角色返回数据库中存储的权限码
     */
    public List<String> getUserAuthorityCodes(Long userId) {
        // 获取用户信息
        SysUser user = userMapper.selectById(userId);
        if (user == null) {
            return new ArrayList<>();
        }
        
        Long tenantId = user.getTenantId();
        SysRole role = null;
        
        // 获取角色
        if (user.getRoleId() != null) {
            role = roleMapper.selectById(user.getRoleId());
        } else if (user.getRole() != null && !user.getRole().isEmpty()) {
            LambdaQueryWrapper<SysRole> roleWrapper = new LambdaQueryWrapper<>();
            roleWrapper.eq(SysRole::getTenantId, tenantId)
                       .eq(SysRole::getRoleCode, user.getRole());
            role = roleMapper.selectOne(roleWrapper);
        }
        
        // 如果是固定权限角色，返回空列表（权限由前端根据角色类型自动计算）
        if (role != null && role.getFixedPermission() != null && role.getFixedPermission() == 1) {
            return new ArrayList<>();
        }
        
        // 如果是可编辑角色，返回数据库中存储的权限码
        if (role != null && role.getPermissions() != null && !role.getPermissions().isEmpty()) {
            try {
                return objectMapper.readValue(role.getPermissions(), new TypeReference<List<String>>() {});
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        
        return new ArrayList<>();
    }
}

